const Koa = require('koa')
const Router = require('koa-router')
const cors = require('@koa/cors')
const KoaBody = require('koa-body')
const KoaJson = require('koa-json')

const koa = new Koa()
const router = new Router()

// koa.use(async (ctx) => {
//     ctx.body = "Hello World!";
// })

router.prefix('api')

router.get('/', (ctx) => {
    console.log(ctx)
    console.log(ctx.request)
    ctx.body = "Hello World!"
})

router.post('/post', async (ctx) => {
    let {body} = ctx.request;
    console.log(body)
    console.log(ctx.request)
    ctx.body = {
        body
    }
})

router.get('/api', async (ctx) => {
    const params = ctx.request.query
    console.log(params)
    console.log(params.name,params.age)
    ctx.body = {
        name: params.name,
        age: params.age
    }
})

router.get('/async', async (ctx) => {
    let result = await new Promise((resolve) => {
        setTimeout(function () {
            resolve('Hello World 2s later!')
        },2000)
    })
    ctx.body = result
})

koa.use(KoaBody())
koa.use(cors())
koa.use(KoaJson({pretty:false, params: 'pretty'}))

koa.use(router.routes()).use(router.allowedMethods())

koa.listen(3000)